package com.pyb.common.response;

import com.google.common.collect.Lists;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.List;

import javax.annotation.Resource;

/**
 * ResponseBodyWrapFactoryBean
 *
 * @author chuchen.zhang
 * @date 17-2-26 上午3:28
 */
public class ResponseBodyWrapFactoryBean implements InitializingBean {

	@Resource
	private RequestMappingHandlerAdapter adapter;

	public void afterPropertiesSet() throws Exception {
		List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter.getReturnValueHandlers();
		List<HandlerMethodReturnValueHandler> handlers = Lists.newArrayList(returnValueHandlers);
		handlers = decorateHandlers(handlers);
		adapter.setReturnValueHandlers(handlers);
	}

	private List<HandlerMethodReturnValueHandler> decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
		handlers = Lists.newArrayList(handlers);
		for (HandlerMethodReturnValueHandler handler : handlers) {
			if (handler instanceof RequestResponseBodyMethodProcessor) {
				//用自己的ResponseBody包装类替换掉框架的，达到返回Result的效果
				ResponseBodyWrapHandler decorator = new ResponseBodyWrapHandler(handler);
				int index = handlers.indexOf(handler);
				handlers.set(index, decorator);
			}
		}
		return handlers;
	}
}
